package me.gavin.base

import android.app.Activity
import android.content.res.Resources
import android.os.Looper
import me.jessyan.autosize.AutoSizeCompat
import me.jessyan.autosize.AutoSizeConfig
import me.jessyan.autosize.internal.CancelAdapt
import me.jessyan.autosize.internal.CustomAdapt
import me.jessyan.autosize.onAdaptListener
import me.jessyan.autosize.utils.ScreenUtils

object AutoSizer {
    /**
     * AutoSize 兼容部分 rom 分屏&缩放 模式的问题
     * @see https://github.com/JessYanCoding/AndroidAutoSize/issues/66
     */
    fun fixInvalidOnSplit() {
        AutoSizeConfig.getInstance().onAdaptListener = object : onAdaptListener {
            override fun onAdaptBefore(target: Any, activity: Activity) {
                // 使用以下代码, 可支持 Android 的分屏或缩放模式, 但前提是在分屏或缩放模式下当用户改变您 App 的窗口大小时
                // 系统会重绘当前的页面, 经测试在某些机型, 某些情况下系统不会重绘当前页面, ScreenUtils.getScreenSize(activity) 的参数一定要不要传 Application!!!
                AutoSizeConfig.getInstance().screenWidth = ScreenUtils.getScreenSize(activity)[0]
                AutoSizeConfig.getInstance().screenHeight = ScreenUtils.getScreenSize(activity)[1]
            }

            override fun onAdaptAfter(target: Any, activity: Activity) {}
        }
    }
}

/**
 * AutoSize 在任何情况下本来适配正常的布局突然出现适配失效 的 万能解决方案
 * @see https://github.com/JessYanCoding/AndroidAutoSize/issues/13
 */
fun Resources.fixInvalidOnAny(activity: Activity) = also {
    if (Looper.myLooper() != Looper.getMainLooper()) return@also
    if (activity is CustomAdapt) {
        AutoSizeConfig.getInstance().isExcludeFontScale = true // 屏蔽系统字体大小影响
        AutoSizeCompat.autoConvertDensityOfCustomAdapt(it, activity)
        // AutoSizeCompat.autoConvertDensity(it, 667f, false) // CustomAdapt
    } else if (activity !is CancelAdapt) {
        AutoSizeConfig.getInstance().isExcludeFontScale = true // 屏蔽系统字体大小影响
        AutoSizeCompat.autoConvertDensityOfGlobal(it) // 默认
    }
}